package com.ruirenyun.handler;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description
 * @Author RenPing
 * @Date 2020/7/31 11:51
 */
@JsonComponent
public class JsonDateDeserializer extends JsonDeserializer<Date> {
    public static final Logger log = LogManager.getLogger(JsonDateDeserializer.class);
    private String[] patterns = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd","yyyy-MM"};

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String dateStr = jsonParser.getText();
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }

        return parseDate(dateStr, patterns);
    }

    private Date parseDate(String dateStr, String[] patterns) {
        for (String pattern : patterns) {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            try {
                return sdf.parse(dateStr);
            } catch (ParseException e) {
            }
        }
        return null;
    }
}
